package com.util;

import com.alibaba.fastjson.JSON;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * 工具类
 *
 * @author wang_
 * @version 2024.3.4.1
 * @description
 * @date 2025/7/2
 */
public class Util {
	protected static final Logger LOG = LogManager.getLogger(Util.class);
	
	/// 获取真实路径
	public static String getRealPath(HttpSession session, String path) {
		return session.getServletContext().getRealPath("/" + path);
	}
	
	/// 获取真实路径
	public static String getRealPath(HttpServletRequest request, String path) {
		return request.getServletContext().getRealPath("/" + path);
	}
	
	/// 对象转JSON
	public static String getJson(Object o) {
		return JSON.toJSONString(o);
	}
	
	
	/**
	 * 上传文件
	 *
	 * @param path    路径
	 * @param part    文件
	 * @param session session
	 */
	public static void uploadFile(String path, Part part, HttpSession session) {
		FileTool fileTool = new FileTool(session, path);
		PartTool partTool = new PartTool(part, session, path);
		uploadFile(path, part, fileTool, partTool);
	}
	
	/**
	 * 上传文件
	 *
	 * @param path 路径
	 * @param part 文件
	 */
	public static void uploadFile(String path, Part part, FileTool fileTool, PartTool partTool) {
		String fileName = partTool.getFileName();
		String uploadFilePath = fileTool.getUploadFilePath();
		try {
			partTool.write(uploadFilePath + File.separator + fileName);
		} catch (IOException e) {
			LOG.error("异常：上传文件失败");
			LOG.error(e);
		}
	}
	
	/**
	 * 上传文件
	 *
	 * @param path    路径
	 * @param part    文件
	 * @param request request
	 */
	public static void uploadFile(String path, Part part, HttpServletRequest request) {
		FileTool fileTool = new FileTool(request, path);
		PartTool partTool = new PartTool(part, request, path);
		uploadFile(path, part, fileTool, partTool);
	}
}
